﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace WX_DatToImg
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public int imgConvertNum;

        public bool isStart = true;
        public string ext { get; set; }
        public byte key { get; set; } //用于解密的数字


        public void convert(string datfile)
        {
            FileInfo fileInfo = new FileInfo(datfile);

            byte[] dat = File.ReadAllBytes(fileInfo.FullName);

            getExt(dat[0], dat[1]);

            for (int i = 0; i < dat.Length; i++)
            {
                dat[i] ^= key;
            }

            string imgPath = Path.Combine(outPathText.Text);
            if (!Directory.Exists(imgPath)) Directory.CreateDirectory(imgPath);

            string imgFullPath = Path.Combine(imgPath, fileInfo.Name + ext);
            if (!File.Exists(imgFullPath))
            {
                File.WriteAllBytes(imgFullPath, dat);
                imgConvertNum += 1;
                convertNum.BeginInvoke((MethodInvoker) delegate { convertNum.Text = imgConvertNum.ToString(); });
            }
        }

        private void getExt(byte key1, byte key2)
        {
            byte jkey1 = (byte) (key1 ^ 0xff);
            byte jkey2 = (byte) (key2 ^ 0xD8);

            if (jkey1 == jkey2)
            {
                key = jkey1;
                ext = ".jpg";
            }

            byte gkey1 = (byte) (key1 ^ 0x47);
            byte gkey2 = (byte) (key2 ^ 0x49);

            if (gkey1 == gkey2)
            {
                key = gkey1;
                ext = ".gif";
            }

            byte pkey1 = (byte) (key1 ^ 0x89);
            byte pkey2 = (byte) (key2 ^ 0x50);
            if (pkey1 == pkey2)
            {
                key = pkey1;
                ext = ".png";
            }

            byte bkey1 = (byte) (key1 ^ 0x42);
            byte bkey2 = (byte) (key2 ^ 0x4d);

            if (bkey1 == bkey2)
            {
                key = bkey1;
                ext = ".bmp";
            }
        }


        private void openFolder_Click(object sender, EventArgs e)
        {
            if (DialogResult.OK.Equals(openFolderDialog.ShowDialog()))
            {
                filePathText.Text = openFolderDialog.SelectedPath;
                filePathText.Focus();
                outPathText.Text = openFolderDialog.SelectedPath + "\\CovertImage";
                outPathText.Focus();
            }
        }

        private void convertBtn_Click(object sender, EventArgs e)
        {
            if (convertBtn.Text == "停止")
            {
                isStart = false;
                convertBtn.Text = "开始转换";
                return;
            }

            isStart = true;
            Thread thread = new Thread(bengin);
            thread.Start();
        }

        private void bengin()
        {
            try
            {
                convertBtn.BeginInvoke((MethodInvoker) delegate { convertBtn.Text = "停止"; });
                string filePath = filePathText.Text;
                string outPath = outPathText.Text;
                if (filePath.Length == 0 || outPath.Length == 0)
                {
                    MessageBox.Show("路径不能为空！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                DirectoryInfo dir = new DirectoryInfo(filePath);
                if (!dir.Exists)
                {
                    MessageBox.Show("目录不存在！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                imgConvertNum = 0;
                convertNum.BeginInvoke((MethodInvoker) delegate { convertNum.Text = imgConvertNum.ToString(); });
                eachDirFile(filePath);
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message, "异常", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            convertBtn.BeginInvoke((MethodInvoker) delegate { convertBtn.Text = "开始转换"; });
        }

        private void eachDirFile(string folderPath)
        {
            Queue<string> queue = new Queue<string>();
            queue.Enqueue(folderPath);
            while (queue.Count > 0)
            {
                DirectoryInfo dirInfo = new DirectoryInfo(queue.Dequeue());
                foreach (DirectoryInfo dirchildInfo in dirInfo.GetDirectories())
                {
                    queue.Enqueue(dirchildInfo.FullName);
                }

                foreach (FileInfo item in dirInfo.GetFiles())
                {
                    if (".dat" != item.Extension)
                    {
                        continue;
                    }

                    if (!isStart)
                    {
                        return;
                    }

                    convert(item.FullName);
                }
            }

            MessageBox.Show("转换完成！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("explorer.exe", "https://gitee.com/su-qiu/WXDatToImg");
        }
    }
}